package www.webols.repository;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import www.webols.utils.StreamTool;

public class ImageCache {
	String path;
	public ImageCache(){
		path = android.os.Environment.getExternalStorageDirectory()
				+ "/weibols/images";
		File root=new File(path);
		if(!root.exists()){
			root.mkdir();
		}
		File thumb=new File(path+"/thumb");
		File middle=new File(path+"/middle");
		if(!thumb.exists())
			thumb.mkdir();
		if(!middle.exists())
			middle.mkdir();
	}
	public void setThumbImage(String name,byte[] data) throws IOException{
		String fullPath=path+"/thumb/"+name;
		this.setImage(fullPath, data);
	}
	public void setMiddleImage(String name,byte[] data) throws IOException{
		String fullPath=path+"/middle/"+name;
		this.setImage(fullPath, data);
	}
	public void setImage(String fullPath,byte[] data) throws IOException{
		File file=new File(fullPath);
		if(file.exists()) return;
		file.createNewFile();
		
		java.io.FileOutputStream out=new FileOutputStream(file);
		out.write(data);
		out.close();
	}
	/**
	 * return null if no cache
	 * @param name
	 * @return
	 */
	public byte[] getThumbImage(String name) throws IOException{
		String fullPath=path+"/thumb/"+name;
		return this.getImage(fullPath);
	}
	public byte[] getMiddleImage(String name) throws IOException{
		String fullPath=path+"/middle/"+name;
		return this.getImage(fullPath);
	}
	public byte[] getImage(String fullPath) throws IOException{
		File file=new File(fullPath);
		if(!file.exists()) return null;
		FileInputStream in=new FileInputStream(file);
		byte[] data=StreamTool.readInputStream(in);
		in.close();
		return data;
	}
}
